﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using LY.Entity;
using LY.Entity.Entities;
using Newtonsoft.Json;

namespace LY.Common
{
    public partial class SmsMessage
    {
        public SmsMessage()
        { } 
        /// <summary>
        /// 检查账户信息是否正确
        /// </summary>
        /// <returns></returns>
        public static bool Exists()
        {
            var siteConfig = (S_Siteconfig)SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath")); 
            const string url = "http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/validateUser"; 
            string result = Utility.HttpPost(url,
                       "account=" + siteConfig.Smsusername + "&password=" + siteConfig.Smspassword + ""); 
            return result=="1";
        }

        /// <summary>
        /// 发送手机短信
        /// </summary>
        /// <param name="mobiles">目标号码,号码与号码之间用 英文; 号分割。</param>
        /// <param name="content">短信内容</param>
        /// <param name="pass">短信通道1验证码通道2广告通道</param>
        /// <param name="msg">返回提示信息</param>
        /// <returns>bool</returns>
        public static bool Send(string mobiles, string content, int pass, out string msg)
        {
            //检查是否设置好短信账号
            if (!Exists())  
            {
                msg = "短信配置参数有误，请完善后再提交！";
                return false;
            }
            //检查手机号码，如果超过2000则分批发送
            int sucCount = 0; //成功提交数量
            string errorMsg = string.Empty; //错误消息
            string[] oldMobileArr = mobiles.Split(';');
            int batch = oldMobileArr.Length / 2000 + 1; //2000条为一批，求出分多少批
            var siteConfig = (S_Siteconfig)SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath")); 
            for (int i = 0; i < batch; i++)
            {
                StringBuilder sb = new StringBuilder();
                int sendCount = 0; //发送数量
                int maxLenght = (i + 1) * 2000; //循环最大的数

                //检测号码，忽略不合格的，重新组合
                for (int j = 0; j < oldMobileArr.Length && j < maxLenght; j++)
                {
                    int arrNum = j + (i * 2000);
                    string pattern = @"^1\d{10}$";
                    string mobile = oldMobileArr[arrNum].Trim();
                    Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //正则表达式实例，不区分大小写
                    Match m = r.Match(mobile); //搜索匹配项
                    if (m != null)
                    {
                        sendCount++;
                        sb.Append(mobile + ";");
                    }
                }

                //发送短信
                if (sb.ToString().Length > 0)
                {
                    try
                    {
                        //目标号码,号码与号码之间用 英文; 号分割。
                        string result = Utility.HttpPost(siteConfig.Smsapiurl,
                            "account=" + siteConfig.Smsusername + "&password=" + siteConfig.Smspassword + "&destmobile=" + Utility.DelLastChar(sb.ToString(),";") + "&encode=utf8&msgText=" + Utility.UrlEncode(content));
                        #region 错误验证
                        sucCount = Convert.ToInt32(result);
                        if (sucCount <= 0)
                        {
                            switch (result)
                            {
                                case "-1":
                                    errorMsg = "余额不足";
                                    break;
                                case "-2":
                                    errorMsg = "帐号或密码错误";
                                    break;
                                case "-3":
                                    errorMsg = "帐号或密码错误";
                                    break;
                                case "-4":
                                    errorMsg = "帐号或密码错误";
                                    break;
                                case "-5":
                                    errorMsg = "其他错误，一般为网络问题，IP受限等";
                                    break;
                                case "-6":
                                    errorMsg = "其他错误，一般为网络问题，IP受限等";
                                    break;
                                case "-7":
                                    errorMsg = "其他错误，一般为网络问题，IP受限等";
                                    break;
                                case "-8":
                                    errorMsg = "用户通道设置不对，需要设置三个通道";
                                    break;
                                case "-9":
                                    errorMsg = "捕获未知异常";
                                    break;
                                case "-10":
                                    errorMsg = "超过最大定时时间限制";
                                    break;
                                case "-11":
                                    errorMsg = "目标号码在黑名单里";
                                    break;
                                case "-12":
                                    errorMsg = "消息内容包含禁用词语";
                                    break;
                                case "-13":
                                    errorMsg = "消息内容包含禁用词语";
                                    break;
                                case "-15":
                                    errorMsg = "个性化号码数量和内容数量不一致";
                                    break;
                                case "-14":
                                    errorMsg = "找不到对应的Channel ID";
                                    break;
                                case "-17":
                                    errorMsg = "找不到对应的Channel ID";
                                    break;
                                case "-18":
                                    errorMsg = "找不到对应的Channel ID";
                                    break;
                                case "-19":
                                    errorMsg = "必须为POST提交";
                                    break;
                                case "-20":
                                    errorMsg = "超速提交(一般为每秒一次提交)";
                                    break;
                                default:
                                    errorMsg = "超出想象的错误.......";
                                    break;
                            }
                        } 
                        #endregion

                       
                    }
                    catch
                    {
                        //没有动作
                    }
                }
            } 
            //返回状态
            if (sucCount > 0)
            {
                msg = "成功提交,本批次的任务ID为" + sucCount + "";
                return true;
            }
            msg = errorMsg;
            return false;
        }

        /// <summary>
        /// 查询账户剩余短信数量
        /// </summary>
        public static SmsUserInfo GetAccountQuantity()
        {
            //检查是否设置好短信账号
            if (!Exists())
            {
              
                return null;
            }
            try
            {
                var siteConfig = (S_Siteconfig)SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath")); 
                const string url = "http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/getUserInfo";
                string result = Utility.HttpPost(url,
                       "account=" + siteConfig.Smsusername + "&password=" + siteConfig.Smspassword +""); 

               var doc = new XmlDocument();
                doc.LoadXml(result);
                XmlNodeList xxList = doc.GetElementsByTagName("userinfo"); //取得节点名为Object的集合
                SmsUserInfo userinfo = new SmsUserInfo();
                foreach (XmlNode xxNode in xxList)  //xxNode 是每一个<CL>...</CL>体
                {
                    userinfo.vip = xxNode["vip"].InnerText;
                    userinfo.usertype = xxNode["usertype"].InnerText;
                    userinfo.userId = xxNode["userId"].InnerText;
                    userinfo.remainFee = xxNode["remainFee"].InnerText;
                    userinfo.mmsrate = xxNode["mmsrate"].InnerText;
                    XmlNodeList childList = xxNode["Channels"].ChildNodes;  
                    //foreach (XmlNode  item in childList)
                    //{
                    //    Channel item1 = new Channel(); 
                    //    item1.Id = item["Id"].InnerText;
                    //    item1.MsgCount = item["MsgCount"].InnerText;
                    //    item1.MsgCount_l = item["MsgCount_l"].InnerText;
                    //    item1.name = item["name"].InnerText; 
                    //    userinfo.Channels.Add(item1);
                    //} 
                }
                return userinfo; 

              ////  var jsonText = JsonConvert.SerializeXmlNode(doc["userinfo"]);
              //  SmsUserInfo userinfo = XmlUtil.DeserializeFromXml(doc["userinfo"].InnerXml, typeof(SmsUserInfo)) as SmsUserInfo;  
              //  //var  userinfo = JsonConvert.DeserializeObject<SmsUserInfo>(jsonText); 
                return userinfo;
            }
            catch
            { 
                return null;
            }
        }

        /// <summary>
        /// 查询已发送数量
        /// </summary>
        public static int GetSendQuantity(out string code)
        {
            //检查是否设置好短信账号
            if (!Exists())
            {
                code = "115";
                return 0;
            }
            try
            {
                var siteConfig = (S_Siteconfig)SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath")); 
                string result = Utility.HttpPost(siteConfig.Smsapiurl, "cmd=se&uid=" + siteConfig.Smsusername + "&pwd=" + siteConfig.Smspassword);
                string[] strArr = result.Split(new string[] { "||" }, StringSplitOptions.None);
                if (strArr[0] != "100")
                {
                    code = strArr[0];
                    return 0;
                }
                code = strArr[0];
                return Utility.StrToInt(strArr[1], 0);
            }
            catch
            {
                code = "115";
                return 0;
            }
        }

    }

    //public class siteConfig
    //{
    //    public static string smsapiurl = "http://www.jianzhou.sh.cn/JianzhouSMSWSServer/http/sendBatchMessage/";
    //    public static string smsusername = "jzyy608";
    //    public static string smspassword = "888666"; // Utility.MD5("123456");
    //}

    public class XmlUtil
    {
        //反序列化
        //接收2个参数:xmlFilePath(需要反序列化的XML文件的绝对路径),type(反序列化XML为哪种对象类型)
        public static object DeserializeFromXml(string xmlFilePath, Type type)
        {
            object result = null; 
                using (StreamReader reader = new StreamReader(@xmlFilePath))
                {
                    XmlSerializer xs = new XmlSerializer(type);
                    result = xs.Deserialize(reader);
                }
          
            return result;
        }
        public static void SerializeToXml(object srcObject, Type type, string xmlFilePath, string xmlRootName)
        {
            if (srcObject != null && !string.IsNullOrEmpty(xmlFilePath))
            {
                type = type != null ? type : srcObject.GetType();

                using (StreamWriter sw = new StreamWriter(xmlFilePath))
                {
                    XmlSerializer xs = string.IsNullOrEmpty(xmlRootName) ?
                        new XmlSerializer(type) :
                        new XmlSerializer(type, new XmlRootAttribute(xmlRootName));
                    xs.Serialize(sw, srcObject);
                }
            }
        }
    }
}
